import { ref, computed, inject } from 'vue'
import translationService from '../services/translationService.js'

// 全局翻译状态
const isTranslating = ref(false)
const translationCache = ref(new Map())

export function useTranslation() {
  // 获取全局状态
  const globalState = inject('globalState', {
    currentLanguage: 'zh',
    autoTranslateEnabled: true,
    isTranslating: false
  })

  // 当前语言
  const currentLanguage = computed(() => globalState.currentLanguage || 'zh')

  // 同步翻译函数 - 用于模板中
  const ts = (text, fallback = null) => {
    if (!text) return ''
    
    // 如果是中文，直接返回
    if (currentLanguage.value === 'zh') {
      return text
    }

    // 检查缓存
    const cacheKey = translationService.getCacheKey(text, currentLanguage.value, 'zh')
    const cached = translationService.getCache().get(cacheKey)
    
    if (cached) {
      return cached
    }

    // 如果没有缓存，异步翻译并返回原文
    if (globalState.autoTranslateEnabled) {
      translateAsync(text, currentLanguage.value)
    }
    
    return fallback || text
  }

  // 异步翻译函数
  const t = async (text, targetLang = null, sourceLang = 'zh') => {
    if (!text) return ''
    
    const target = targetLang || currentLanguage.value
    
    if (target === sourceLang) {
      return text
    }

    try {
      isTranslating.value = true
      const result = await translationService.translate(text, target, sourceLang)
      
      // 更新缓存引用
      translationCache.value = translationService.getCache()
      
      return result
    } catch (error) {
      console.error('翻译失败:', error)
      return text
    } finally {
      isTranslating.value = false
    }
  }

  // 异步翻译（不阻塞UI）
  const translateAsync = async (text, targetLang = null, sourceLang = 'zh') => {
    try {
      await t(text, targetLang, sourceLang)
      // 触发响应式更新
      translationCache.value = new Map(translationService.getCache())
    } catch (error) {
      console.error('异步翻译失败:', error)
    }
  }

  // 批量预翻译
  const preTranslate = async (texts, targetLang = null, sourceLang = 'zh') => {
    const target = targetLang || currentLanguage.value
    
    if (target === sourceLang) return

    try {
      isTranslating.value = true
      console.log(`开始预翻译 ${texts.length} 个文本到 ${target}`)
      
      const promises = texts.map(text => 
        translationService.translate(text, target, sourceLang)
      )
      
      await Promise.all(promises)
      
      // 更新缓存引用
      translationCache.value = new Map(translationService.getCache())
      
      console.log('预翻译完成')
    } catch (error) {
      console.error('预翻译失败:', error)
    } finally {
      isTranslating.value = false
    }
  }

  // 切换语言
  const setLanguage = (lang) => {
    if (globalState.currentLanguage !== undefined) {
      globalState.currentLanguage = lang
    }
    console.log(`语言切换到: ${lang}`)
  }

  // 切换自动翻译
  const toggleAutoTranslate = () => {
    if (globalState.autoTranslateEnabled !== undefined) {
      globalState.autoTranslateEnabled = !globalState.autoTranslateEnabled
    }
  }

  // 清除翻译缓存
  const clearTranslationCache = () => {
    translationService.clearCache()
    translationCache.value = new Map()
    console.log('翻译缓存已清除')
  }

  // 获取翻译统计
  const getTranslationStats = () => {
    return {
      cacheSize: translationService.getCache().size,
      currentProvider: translationService.getStats().currentProvider,
      isTranslating: isTranslating.value
    }
  }

  return {
    // 核心函数
    ts,           // 同步翻译函数（用于模板）
    t,            // 异步翻译函数
    preTranslate, // 批量预翻译
    
    // 状态
    currentLanguage,
    isTranslating: computed(() => isTranslating.value || globalState.isTranslating),
    autoTranslateEnabled: computed(() => globalState.autoTranslateEnabled),
    translationCache,
    
    // 操作函数
    setLanguage,
    toggleAutoTranslate,
    clearTranslationCache,
    getTranslationStats,
    translateAsync
  }
} 